package designpattern.iterator.fib;

import java.util.Iterator;
import java.util.stream.Stream;

public class Fib {

    public static Stream<Long> fibonacciStreamIterate() {
        return Stream.iterate(new long[] { 0, 1 }, pair -> new long[] { pair[1], pair[0] + pair[1] })
                .map(pair -> pair[0]);
    }

    public static void main(String[] args) {
        Iterator<Integer> iterator = new FibIterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next > 100)
                break;
            System.out.print(next+ " ");
        }
        System.out.println();

        fibonacciStreamIterate()
                .takeWhile(x -> x <= 100)
                .forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
}

// 斐波那级数的迭代器
class FibIterator implements Iterator<Integer> {

    private int a = 0;
    private int b = 1;

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public Integer next() {
        int result = a;
        a = b;
        b = a + result;
        return result;
    }
}
